import { NextRequest, NextResponse } from 'next/server'
import { getFavorites, getUsers } from '@/lib/database'
import { withErrorHandling } from '@/lib/auth-middleware'

export const GET = withErrorHandling(async (request: NextRequest, context: any) => {
  // 从URL中提取工具ID
  const url = new URL(request.url)
  const pathSegments = url.pathname.split('/')
  const toolId = pathSegments[pathSegments.length - 3] // stats前面的ID

  if (!toolId) {
    return NextResponse.json(
      { error: '工具ID不能为空' },
      { status: 400 }
    )
  }

  try {
    const [favorites, users] = await Promise.all([
      getFavorites(),
      getUsers()
    ])

    const toolFavorites = favorites.filter(fav => fav.toolId === toolId)

    if (toolFavorites.length === 0) {
      return NextResponse.json({
        success: true,
        data: {
          totalFavorites: 0,
          recentFavorites: 0,
          favoriteUsers: []
        }
      })
    }

    // 计算最近7天的收藏数
    const sevenDaysAgo = new Date()
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
    
    const recentFavorites = toolFavorites.filter(fav => 
      new Date(fav.createdAt) >= sevenDaysAgo
    ).length

    // 获取收藏用户信息
    const favoriteUsers = toolFavorites
      .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
      .slice(0, 10) // 只取最近10个
      .map(fav => {
        const user = users.find(u => u.id === fav.userId)
        return {
          id: fav.userId,
          name: user?.name || '未知用户',
          avatar: user?.avatar,
          favoriteDate: fav.createdAt
        }
      })

    return NextResponse.json({
      success: true,
      data: {
        totalFavorites: toolFavorites.length,
        recentFavorites,
        favoriteUsers
      }
    })
  } catch (error) {
    console.error('获取收藏统计失败:', error)
    return NextResponse.json(
      { error: '服务器内部错误' },
      { status: 500 }
    )
  }
})
